package com.zdkj.subway.rca.controller;

import com.zdkj.common.core.util.R;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkBackElectronicBillBocTmp;
import com.zdkj.subway.rca.entity.SwCkBackElectronicBillCcbTmp;
import com.zdkj.subway.rca.entity.SwCkBankCashPaymentNoteTmp;
import com.zdkj.subway.rca.entity.SwCkElectronicReceiptTmp;
import com.zdkj.subway.rca.service.*;
import com.zdkj.subway.rca.util.MyDateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 收入对账大数据量导入，后台批量处理
 * 文件上传自动解析
 */
@RestController
@RequestMapping("/swCkAutoUploadFileResolve" )
@Api(value = "swCkAutoUploadFileResolve", tags = "文件上传自动解析")
@Slf4j
public class SwCkAutoUploadFileResolveController {

    //20多个对账确认表
	@Autowired
    private SwCkBankVerifyPaymentService swCkBankVerifyPaymentService;
    @Resource
    private SwCkBankVerifyPaymentController swCkBankVerifyPaymentController;
    //BOM小额支付平台
    @Autowired
    private SwCkBomSmallPaymentService swCkBomSmallPaymentService;
    @Resource
    private SwCkBomSmallPaymentController swCkBomSmallPaymentController;
    //多元化支付平台
    @Autowired
    private SwCkDistinctPaymentService swCkDistinctPaymentService;
    @Resource
    private SwCkDistinctPaymentController swCkDistinctPaymentController;
    //现金缴款单
    @Autowired
    private SwCkBankCashPaymentNoteTmpService swCkBankCashPaymentNoteTmpService;
    @Resource
    private SwCkBankCashPaymentNoteTmpController swCkBankCashPaymentNoteTmpController;
    //银行电子账单
    @Autowired
    private SwCkBackElectronicBillBocTmpService swCkBackElectronicBillBocTmpService;
    @Resource
    private SwCkBackElectronicBillBocTmpController swCkBackElectronicBillBocTmpController;

    @Autowired
    private SwCkBackElectronicBillCcbTmpService swCkBackElectronicBillCcbTmpService;
    @Resource
    private SwCkBackElectronicBillCcbTmpController swCkBackElectronicBillCcbTmpController;
    //电子回执单
    @Autowired
    private SwCkElectronicReceiptTmpService swCkElectronicReceiptTmpService;
    @Resource
    private SwCkElectronicReceiptTmpController swCkElectronicReceiptTmpController;
    //机场线日报表
    @Autowired
    private SwCkOthenTicketRevenueManagementTmpService swCkOthenTicketRevenueManagementTmpService;
    @Resource
    private SwCkOthenTicketRevenueManagementController swCkOthenTicketRevenueManagementController;
    //9号线日报表
    @Autowired
    private SwCkOthenXaztTicketRevenueManagementTmpService swCkOthenXaztTicketRevenueManagementTmpService;
    @Resource
    private SwCkOthenXaztTicketRevenueManagementController swCkOthenXaztTicketRevenueManagementController;
    //应急纸票
    @Autowired
    private SwCkOthenYjzpManagementTmpService swCkOthenYjzpManagementTmpService;
    @Resource
    private SwCkOthenYjzpManagementController swCkOthenYjzpManagementController;
    
    /**
     * 批量导入文件
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "批量导入文件", notes = "批量导入文件")
    @Inner
    @PostMapping(value = "/autoUploadFileResolve")
    public R autoUploadFileResolve() throws Exception {

        //25个对账表
        Map<String, String> mapTable1 = new HashMap<>();
        List<Map<String,String>> list = swCkBankVerifyPaymentService.getSwCkBankVerifyPaymentConfirmTableListPre();
        list.forEach(x -> {
            mapTable1.put(x.get("tableName"),x.get("verfiyConfirmFlag"));
        });
        //现金交款单
        Map<String, String> mapTable2 = new HashMap<>();
        mapTable2.put("sw_ck_bank_cash_payment_note","sw_ck_bank_cash_payment_note");

        //Bom小额支付平台
        Map<String, String> mapTable3 = new HashMap<>();
		//微信
        mapTable3.put("sw_ck_bom_small_payment_wechat","1");
		//支付宝
        mapTable3.put("sw_ck_bom_small_payment_alipay","2");

        //多元化支付平台
        Map<String, String> mapTable4 = new HashMap<>();
		//微信支付宝银联数字人民币
        mapTable4.put("sw_ck_distinct_payment_qr","1");
		//TVM电子平台
        mapTable4.put("sw_ck_distinct_payment_tvm","2");
		//人脸
        mapTable4.put("sw_ck_distinct_payment_face","3");
		//应急及互联互通
		mapTable4.put("sw_ck_distinct_payment_connectivity","4");
        //银行电子账单
        Map<String, String> mapTable5 = new HashMap<>();
		//中国银行
        mapTable5.put("sw_ck_back_electronic_bill_boc","1");
		//建设银行
        mapTable5.put("sw_ck_back_electronic_bill_ccb","2");
        //电子回执单
        Map<String, String> mapTable6 = new HashMap<>();
        mapTable6.put("sw_ck_electronic_receipt","sw_ck_electronic_receipt");
        //机场城际
        Map<String, String> mapTable7 = new HashMap<>();
        mapTable7.put("sw_ck_othen_ticket_revenue_management","sw_ck_othen_ticket_revenue_management");
        //西安中铁
        Map<String, String> mapTable8 = new HashMap<>();
        mapTable8.put("sw_ck_othen_xazt_ticket_revenue_management","sw_ck_othen_xazt_ticket_revenue_management");
        //应急纸票管理
        Map<String, String> mapTable9 = new HashMap<>();
        mapTable9.put("sw_ck_othen_yjzp_management","sw_ck_othen_yjzp_management");
        try {

            String encoding="UTF-8";
            Map<String, String> mapfile = new HashMap<>();
            //获取文件存储位置
            List<Map<String,String>> autoUploadFileResolveList = swCkBankVerifyPaymentService.getSwCkAutoUploadFileResolveListPre();
            autoUploadFileResolveList.forEach(x -> {
                mapfile.put(x.get("fileName"),x.get("verfiyConfirmFile"));
            });
			//正常存储路径从字典获取
            String filePath = mapfile.get("file_storage_path"); 
			//异常存储路径从字典获取
            String toPath = mapfile.get("file_error_path"); 
			//获取路径 
            File f = new File(filePath);
            if (!f.exists()) {
                log.info(filePath + " not exists");
                return null;
            }

            File fa[] = f.listFiles();
			//循环遍历
            for (int i = 0; i < fa.length; i++) {
				//获取数组中的第i个
                File fs = fa[i];
                if (fs.isDirectory()) {
					//如果是目录直接忽略
                    continue;
                } else {

                    String initFileName = fs.getName();
                    String name = initFileName.substring(initFileName.indexOf("."));
                    if(name.equals(".xls") || name.equals(".xlsx")){
                        String initFile = initFileName.substring(0,initFileName.lastIndexOf("."));
                        String tableName = initFile.split("-")[0];
                        //把file类型转为MultipartFile
                        FileItem fileItem = this.getMultipartFile(fs, "templFileItem");
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        Object data = null;
                        //确认对账表
                        if (mapTable1.containsKey(tableName)) {
							//拿到字典value
                            String verfiyConfirmFlag = mapTable1.get(tableName);
                            try {
                                swCkBankVerifyPaymentService.saveBatchWithExcel(multipartFile, verfiyConfirmFlag);
                                data = swCkBankVerifyPaymentController.saveBatchOk(verfiyConfirmFlag).getData();
                                if (data instanceof Boolean) {
                                    boolean isOk = (boolean) data;
                                    if (isOk) {
                                        //执行完删除
                                        fs.delete();
                                    }
                                }
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
                          //现金缴款单
                        } else if (mapTable2.containsKey(tableName)) {
                            try {
                                String startDate = "";
                                String endDate = "";
								//包含现金缴款单
                                if (initFileName.contains("sw_ck_bank_cash_payment_note")) {
                                    //获取开始时间和结束时间，这里要增加异常处理，如果文件名没有日期范围会有异常，且日期格式需要验证
                                    startDate = initFile.split("-")[1];
                                    endDate = initFile.split("-")[2];
                                    Boolean a = startDate.length()==8 && endDate.length()==8;
                                    int result = endDate.compareTo(startDate);
                                    if(a && result >= 0){
                                        startDate = MyDateUtil.String8TurnDate(startDate);
                                        endDate = MyDateUtil.String8TurnDate(endDate);
                                        swCkBankCashPaymentNoteTmpService.saveBatchWithExcel(fs, startDate, endDate);
                                        final SwCkBankCashPaymentNoteTmp obj = ObjectUtils.getDefaultObj(SwCkBankCashPaymentNoteTmp.class);
                                        swCkBankCashPaymentNoteTmpService.saveBatchWithExcelOk(obj.getCreatorId());
                                        //执行完删除
                                        fs.delete();
                                    }else {
                                        moveFile(toPath,fs);
                                    }
                                }else {
                                    moveFile(toPath,fs);
                                }
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
							//bom小额支付平台
                        } else if (mapTable3.containsKey(tableName)) {
                            try {
								//拿到value
                                String verfiyConfirmFlag = mapTable3.get(tableName);
                                swCkBomSmallPaymentService.saveBatchWithExcel(multipartFile, verfiyConfirmFlag);
                                swCkBomSmallPaymentController.saveBatchOk(verfiyConfirmFlag);
                                //执行完删除
                                fs.delete();
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
							//多元化支付平台
                        } else if (mapTable4.containsKey(tableName)) {
                            try {
								//拿到value
                                String verfiyConfirmFlag = mapTable4.get(tableName);
                                swCkDistinctPaymentService.saveBatchWithExcel(multipartFile, verfiyConfirmFlag);
                                swCkDistinctPaymentController.saveBatchOk(verfiyConfirmFlag);
                                //执行完删除
                                fs.delete();
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
							//银行电子账单
                        } else if (mapTable5.containsKey(tableName)) {
                            try {
								//拿到value
                                String verfiyConfirmFlag = mapTable5.get(tableName);
								//1代表中国银行，2代表建设银行
                                if("1".equals(verfiyConfirmFlag)){
                                    swCkBackElectronicBillBocTmpService.saveBatchWithExcel(fs);
                                    final SwCkBackElectronicBillBocTmp obj =  ObjectUtils.getDefaultObj(SwCkBackElectronicBillBocTmp.class);
                                    swCkBackElectronicBillBocTmpService.saveBatchWithExcelOk(obj.getCreatorId());
                                }else {
                                    swCkBackElectronicBillCcbTmpService.saveBatchWithExcel(fs);
                                    final SwCkBackElectronicBillCcbTmp obj =  ObjectUtils.getDefaultObj(SwCkBackElectronicBillCcbTmp.class);
                                    swCkBackElectronicBillCcbTmpService.saveBatchWithExcelOk(obj.getCreatorId());
                                }
                                //执行完删除
                                fs.delete();
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
							//电子回执单
                        } else if (mapTable6.containsKey(tableName)) {
                            try {
                                swCkElectronicReceiptTmpService.saveBatchWithExcel(fs);
                                final SwCkElectronicReceiptTmp obj =  ObjectUtils.getDefaultObj(SwCkElectronicReceiptTmp.class);
                                swCkElectronicReceiptTmpService.saveBatchWithExcelOk(obj.getCreatorId());
                                //执行完删除
                                fs.delete();
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
							//机场城际
                        } else if (mapTable7.containsKey(tableName)) {
                            try {
                                swCkOthenTicketRevenueManagementTmpService.saveBatchWithExcel(fs);
                                swCkOthenTicketRevenueManagementController.saveBatchOk();
                                //执行完删除
                                fs.delete();
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
							//西安中铁9号线
                        } else if (mapTable8.containsKey(tableName)) {
                            try {
                                swCkOthenXaztTicketRevenueManagementTmpService.saveBatchWithExcel(fs);
                                swCkOthenXaztTicketRevenueManagementController.saveBatchOk();
                                //执行完删除
                                fs.delete();
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
							//应急纸票管理
                        } else if (mapTable9.containsKey(tableName)) {
                            try {
                                swCkOthenYjzpManagementTmpService.saveBatchWithExcel(fs);
                                swCkOthenYjzpManagementController.saveBatchOk();
                                //执行完删除
                                fs.delete();
                            } catch (Exception e) {
								//删除或移动文件
                                moveFile(toPath,fs);
                                e.printStackTrace();
                            }
                        }

                    }else {
						//删除或移动文件
                        moveFile(toPath,fs);
                    }
                }
            }

        } catch (Exception e) {
			//读取文件内容出错
            R.failed("读取文件内容出错");
            e.printStackTrace();
        }
        return R.ok();
    }

    /**
     * 删除文件并移动到另一个文件夹下
     * @param toPath
     * @param fs
     */
    private void moveFile(String toPath, File fs) {
        File toFile = new File(toPath + "/" + fs.getName());
        //文件存在
		if (toFile.exists()) {           
			log.info("文件已存在");
		   //删除error目录下的旧文件
            toFile.delete();
            fs.renameTo(toFile);
            //移除成功
			log.info("移动文件成功");
        } else {
            fs.renameTo(toFile);
            log.info("移动文件成功");
        }
    }

    /**
     * 将file转换成fileItem
     * @param file
     * @param fieldName
     * @return
	 *        fileItem文件对象
     */
    private FileItem  getMultipartFile(File file, String fieldName){
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
        //转成文件流方式读取
		int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return item;
    }
}
